package com.huc.rest.init;

import com.alibaba.fastjson.JSONObject;
import com.huc.rest.check.HttpContentChecks;
import com.huc.rest.check.HttpHeaderChecks;
import com.huc.rest.utils.WebUtils;
import com.huc.rest.vo.ApiConfigVO;
import com.huc.rest.vo.ServiceCoreVO;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

public class BaseService {

    protected ServiceCoreVO serviceCoreVO = null;
    private HttpServletRequest request = null;
    private HttpServletResponse response = null;


    private void init(){
        serviceCoreVO = new ServiceCoreVO();
    }

    protected ModelAndView response(int i, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("baseService response......");

        this.request = request;
        this.response = response;

        Object object = null;
        //初始化请求体
        init();
        //校验http请求
        HttpHeaderChecks.getInstance(serviceCoreVO,request).checkRequest();
        //校验请求内容
        ApiConfigVO configVO = HttpContentChecks.getInstance(serviceCoreVO,request).checkContent();


        System.out.println("请求api："+serviceCoreVO.getAction());
        System.out.println("请求内容："+serviceCoreVO.getReqObject());
        System.out.println("请求类与方法："+configVO.getBean()+"-"+configVO.getMethod());

        //执行方法
        execute(configVO.getBean(),configVO.getMethod());




        //返回结果
        object = serviceCoreVO.getResObject();

        WebUtils.getInstance().responseContent(response, getRescontent(object));

        return null;
    }

    private void execute(String bean,String method) {
        serviceCoreVO.setBean(bean+"Action");
        serviceCoreVO.setMethod(method+"V100");
        BaseAction baseAction = new BaseAction();
        serviceCoreVO = baseAction.execute(serviceCoreVO);
    }

    protected String getRescontent(Object object) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("format",serviceCoreVO.getFormat());
        params.put("logno",serviceCoreVO.getOperateLogno());
        params.put("accessId",serviceCoreVO.getAccessId());
        params.put("version",serviceCoreVO.getVersionRequest());
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        jsonObject.put("response",object);
        String rescontent = jsonObject.toJSONString();

        serviceCoreVO.setResContent(rescontent);

        return rescontent;
    }


}
